import logging
from logging.config import dictConfig

from flask import request, g, make_response

import config
from app import create_app
from flask_cors import CORS

# 创建 Flask 应用实例
dictConfig(config.LOGGING)
app = create_app()
CORS(app)

app.config['JSON_AS_ASCII'] = False

from utils.db import client
import redis

app.config['DB'] = client()
app.config['REDIS'] = redis.Redis(host='localhost', port=6379, password='', db=0) ##REDIS配置

@app.before_request
def before_request():
    if request.method == 'OPTIONS': 
        response = make_response()
        response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin')
        response.headers['Access-Control-Allow-Credentials'] = 'true'
        response.headers['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, PUT, DELETE, UPDATE"
        response.headers['Access-Control-Allow-Headers'] = "Authorization, Content-Length, Content-Type, Chat-Token, Admin-Authorization"
        return response

    data = ''
    if request.method == 'POST':
        data = request.json
        logging.info('HTTP REQUEST >> 方法: [{}], 参数: {}, 请求IP: {}'.format(request.path, data, request.remote_addr))
    elif request.method == 'GET':
        logging.info('HTTP REQUEST >> 方法: [{}], 参数: {}, 请求IP: {}'.format(request.full_path, data, request.remote_addr))


@app.after_request
def after_request(response):
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response

if __name__ == '__main__':
    app.run(debug=True, port=5679, host='0.0.0.0')

